package repositories

import (
	"SmartSearch/internal/models"
	"SmartSearch/internal/responses"
	"SmartSearch/pkg/database"
	"fmt"
)

type RoleRepository struct {
}

func (r *RoleRepository) Add(role *models.Role) error {
	return database.DB.Create(&role).Error
}

func (r *RoleRepository) Del(id int64) error {
	return database.DB.Delete(&models.Role{}, id).Error
}

func (r *RoleRepository) FindById(id int64) (*models.Role, error) {
	var role models.Role
	err := database.DB.First(&role, id).Error
	return &role, err
}
func (r *RoleRepository) FindByIds(ids []int64) []*models.Role {
	var roles []*models.Role
	database.DB.Where("id IN ?", ids).Find(&roles)
	return roles
}

func (r *RoleRepository) FindByName(name string) (*models.Role, error) {
	role := &models.Role{}
	err := database.DB.Where("name = ?", name).First(role).Error
	return role, err
}

func (r *RoleRepository) GetList(name string, enable *bool, current int32, pageSize int32) *responses.Page {
	var total int64
	var data []*models.Role
	where := fmt.Sprintf("name LIKE '%s'", "%"+name+"%")
	if enable != nil {
		where += fmt.Sprintf(" AND enable = %t", *enable)
	}
	// 此处用了PostForm的请求方法
	tx := database.DB.Debug().Model(models.Role{}).Where(where) // 查询对应的数据库表
	// 此时的total是查询到的总数
	if err := tx.Count(&total).Error; err != nil {
		fmt.Println("获取总数错误" + err.Error())
		return nil
	}
	offset := (current - 1) * pageSize
	if err := tx.Order("id DESC").Offset(int(offset)).Limit(int(pageSize)).Find(&data).Error; err != nil {
		return nil
	}
	return &responses.Page{
		Current:  current,
		PageSize: pageSize,
		Total:    total,
		Content:  data,
	}
}

func (r *RoleRepository) Update(role *models.Role) error {
	return database.DB.Save(&role).Error
}
